extends CharacterBody2D

# 配置参数
@export var move_speed: int = 128       # 每秒移动像素数
@export var grid_size: int = 64        # 网格尺寸（需与地图对齐）

@onready var sprite: AnimatedSprite2D = $AnimatedSprite2D
@onready var ray: RayCast2D = $RayCast2D
@onready var camera: Camera2D = $Camera2D

# 定义一个变量来存储当前播放的动画名称
var current_animation := ""

# 移动方向枚举
enum Direction { UP, DOWN, LEFT, RIGHT }

var is_moving: bool = false
var target_position: Vector2 = Vector2.ZERO
var can_move: bool = true  # 控制是否可以移动

func _ready():
	target_position = position  # 初始位置同步
	add_to_group("player") #添加将 player 加入指定 group 的代码
	
	# 设置摄像头为当前摄像头
	camera.make_current()
	
	# 连接窗口大小变化信号
	get_viewport().size_changed.connect(_on_viewport_size_changed)
	
	# 初始化摄像头缩放
	_update_camera_zoom()

func _physics_process(delta):
	if !is_moving:
		handle_input()
	else:
		move_towards_target(delta)
		# 在移动过程中也检查输入，为连续移动做准备
		if position == target_position:
			handle_input()

# 输入处理
func handle_input():
	if not can_move:
		return
		
	var input_dir := Vector2(
		Input.get_axis("ui_left", "ui_right"),
		Input.get_axis("ui_up", "ui_down")
	)

	if input_dir != Vector2.ZERO:
		attempt_move(input_dir.normalized())

# 尝试移动
func attempt_move(dir: Vector2):
	ray.target_position = dir * grid_size
	ray.force_raycast_update()
	
	if !ray.is_colliding():
		target_position = position + dir * grid_size
		is_moving = true
		update_animation(dir)
	else:
		# 碰撞时播放受阻动画（可选）
		sprite.play("bump")

# 平滑移动
func move_towards_target(delta):
	var move_distance = move_speed * delta
	var move_vector = (target_position - position).normalized() * move_distance
	
	if position.distance_to(target_position) > move_distance:
		position += move_vector
	else:
		position = target_position
		is_moving = false
		
		# 移动完成后恢复生命值
		if PlayerStatsManager != null:
			PlayerStatsManager.heal_on_walk()
		
		# 移动完成后检查随机遇敌
		check_random_encounter()
		
		# 检查是否还有输入，如果没有才播放idle动画
		var input_dir := Vector2(
			Input.get_axis("ui_left", "ui_right"),
			Input.get_axis("ui_up", "ui_down")
		)
		if input_dir == Vector2.ZERO:
			sprite.play("idle_" + get_direction_suffix())

# 动画更新
func update_animation(dir: Vector2):
	var anim_suffix := "down"
	
	if dir.x > 0:
		anim_suffix = "right"
	elif dir.x < 0:
		anim_suffix = "left"
	elif dir.y > 0:
		anim_suffix = "down"
	elif dir.y < 0:
		anim_suffix = "up"
	# 构建即将播放的动画名称
	var new_animation = "walk_" + anim_suffix

	# 检查当前动画和即将播放的动画是否不同
	if new_animation != current_animation:
		# 如果不同，则播放新动画
		sprite.play(new_animation)
		# 更新当前动画名称
		current_animation = new_animation
			
func check_interaction():
	#var ray = RayCast2D.new()
	ray.target_position = Vector2(grid_size, 0).rotated(rotation)
	if ray.is_colliding():
		var obj = ray.get_collider()
		if obj.has_method("interact"):
			obj.interact()
			
# 获取当前方向后缀
func get_direction_suffix() -> String:
	if sprite.animation.split("_").size() >1:
		return sprite.animation.split("_")[1]
	else:
		return "down"

# 窗口大小变化时调用
func _on_viewport_size_changed():
	_update_camera_zoom()

# 更新摄像头缩放以适应窗口大小
func _update_camera_zoom():
	var viewport_size = get_viewport().get_visible_rect().size
	## 基础分辨率（可以根据需要调整）
	#var base_width = 1920.0
	#var base_height = 1080.0
	#
	## 计算缩放比例，使用较小的比例以确保内容完全可见
	#var scale_x = viewport_size.x / base_width
	#var scale_y = viewport_size.y / base_height
	#var zoom_scale = min(scale_x, scale_y)
	#
	## 设置摄像头缩放
	#camera.zoom = Vector2(zoom_scale, zoom_scale)

# 检查随机遇敌
func check_random_encounter():
	# 只在特定场景中检查遇敌（比如scene2）
	var current_scene = get_tree().current_scene
	if current_scene != null:
	#if current_scene != null and current_scene.scene_file_path == "res://scene/scene2.tscn":
		if BattleManager != null:
			BattleManager.check_random_encounter()

# 设置是否可以移动
func set_can_move(value: bool):
	can_move = value
	if not can_move:
		# 如果禁用移动，立即停止移动并播放idle动画
		if is_moving:
			position = target_position
			is_moving = false
		# 播放idle动画以确保角色停止
		sprite.play("idle_" + get_direction_suffix())
